const fs = require('fs/promises');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const logger = require('../services/logger');

const dbPath = path.join(__dirname, '..', 'data', 'db.json');

// 辅助函数，确保db.json和knowledgeBase数组存在
async function ensureKnowledgeBase() {
    try {
        let db;
        try {
            const data = await fs.readFile(dbPath, 'utf8');
            db = JSON.parse(data);
        } catch (error) {
            db = { articles: [], knowledgeBase: [] };
        }
        
        if (!db.knowledgeBase) {
            db.knowledgeBase = [];
        }
        return db;
    } catch (error) {
        logger.error('读取或初始化数据库时出错:', error);
        throw error;
    }
}

async function writeDb(data) {
  await fs.writeFile(dbPath, JSON.stringify(data, null, 2), 'utf8');
}

// 获取所有素材
const getKnowledgeItems = async (req, res) => {
    try {
        const db = await ensureKnowledgeBase();
        res.status(200).json(db.knowledgeBase || []);
    } catch (error) {
        res.status(500).json({ message: '获取素材库失败' });
    }
};

// 添加新素材
const addKnowledgeItem = async (req, res) => {
    const { content } = req.body;
    if (!content) {
        return res.status(400).json({ message: '素材内容不能为空' });
    }
    try {
        const db = await ensureKnowledgeBase();
        const newItem = {
            id: uuidv4(),
            content,
            createdAt: new Date().toISOString(),
        };
        db.knowledgeBase.push(newItem);
        await writeDb(db);
        logger.info(`新增素材成功: "${content.substring(0, 20)}..."`);
        res.status(201).json(newItem);
    } catch (error) {
        res.status(500).json({ message: '添加素材失败' });
    }
};

// 删除素材
const deleteKnowledgeItem = async (req, res) => {
    const { id } = req.params;
    try {
        const db = await ensureKnowledgeBase();
        const initialLength = db.knowledgeBase.length;
        db.knowledgeBase = db.knowledgeBase.filter(item => item.id !== id);
        
        if (db.knowledgeBase.length === initialLength) {
            return res.status(404).json({ message: '未找到要删除的素材' });
        }

        await writeDb(db);
        logger.info(`删除素材成功, ID: ${id}`);
        res.status(200).json({ message: '删除成功' });
    } catch (error) {
        res.status(500).json({ message: '删除素材失败' });
    }
};

module.exports = { getKnowledgeItems, addKnowledgeItem, deleteKnowledgeItem };
